package cn.tuling.storage.controller;


import cn.tuling.storage.po.Storage;
import cn.tuling.storage.service.StorageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuyanzhao
 * @since 2021-12-25
 */
@RestController
@RequestMapping("/storage")
public class StorageController {
    @Autowired
    private StorageService storageService;

    @PutMapping("/deduct")
    public Boolean deduct(@RequestBody Storage storage) {
        Storage qResult = storageService.getOne(new LambdaQueryWrapper<Storage>().eq(Storage::getCommodityCode, storage.getCommodityCode()));
        if (qResult == null)
            throw new RuntimeException("没有该商品的库存");

        if (storage.getCount() > qResult.getCount())
            throw new RuntimeException("该商品库存不够");

        boolean b = storageService.update(new LambdaUpdateWrapper<Storage>()
                .eq(Storage::getCommodityCode, storage.getCommodityCode())
                .set(Storage::getCount, qResult.getCount() - storage.getCount()));
        return b;
    }
}

